using BunnyEater.Common.ResponseOutput;
using BunnyEater.Domain.Base;
using BunnyEater.Domain.SystemManagement;
using BunnyEater.EntityFrameworkCore;
using BunnyEater.Repository.BaseRepository;
using BunnyEater.Repository.Extensions;
using BunnyEater.Service.SystemManagementService.PermissionsService.Dto;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace BunnyEater.Service.SystemManagementService.PermissionsService
{
    /// <summary>
    /// 权限服务实现，提供权限的增删改查及分页等基础功能
    /// </summary>
    public class PermissionsService : IPermissionsService
    {
        private readonly BunnyEaterContext _bunnyEaterContext;
        private readonly IRepository<Permissions> _permissionsRepository;
        private readonly ILogger<PermissionsService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public PermissionsService(BunnyEaterContext bunnyEaterContext, IRepository<Permissions> permissionsRepository, ILogger<PermissionsService> logger)
        {
            _bunnyEaterContext = bunnyEaterContext;
            _permissionsRepository = permissionsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 分页查询权限列表
        /// </summary>
        public async Task<ResponseReturnsEntity<Page<PermissionsListDto>>> GetPagedPermissionsAsync(PermissionsPagedQueryDto query)
        {
            try
            {
                var permissions = _permissionsRepository.GetListQuery().Where(p => !p.IsDelete);

                if (!string.IsNullOrEmpty(query.SearchKeyword))
                {
                    permissions = permissions.Where(p =>
                        EF.Functions.Like(p.PermissionsName, $"%{query.SearchKeyword}%")
                    );
                }

                if (query.State.HasValue)
                {
                    permissions = permissions.Where(p => p.State == query.State.Value);
                }

                var result = await permissions.ToPagedListAsync(
                    query.PageIndex,
                    query.PageSize,
                    null,
                    p => p.CreateTime,
                    false);

                var dtoPage = new Page<PermissionsListDto>
                {
                    Items = result.Items.Select(p => new PermissionsListDto
                    {
                        Id = p.Id,
                        ParentId = p.ParentId,
                        PermissionsName = p.PermissionsName,
                        PermissionsPath = p.PermissionsPath,
                        SortId = p.SortId,
                        State = p.State,
                        CreateTime = p.CreateTime
                    }).ToList(),
                    PageNumber = result.PageNumber,
                    PageSize = result.PageSize,
                    TotalPages = result.TotalPages,
                    TotalItems = result.TotalItems
                };

                return ResponseReturnsEntity<Page<PermissionsListDto>>.Success(dtoPage);
            }
            catch (Exception ex)
            {
                _logger.LogError($"分页查询权限列表失败: {ex.Message}");
                return ResponseReturnsEntity<Page<PermissionsListDto>>.Fail($"查询失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 新增权限，包含事务处理和异常回滚
        /// </summary>
        /// <param name="permissionsDto">权限信息</param>
        /// <returns>操作结果</returns>
        /// <remarks>
        /// 1. 自动为主键Id赋值Guid字符串。
        /// 2. 包含事务处理，失败自动回滚。
        /// 3. 捕获数据库异常和通用异常，记录详细日志。
        /// </remarks>
        public async Task<ResponseReturnsEntity<bool>> AddPermissions(PermissionsListDto permissionsDto)
        {
            using var transaction = await _bunnyEaterContext.Database.BeginTransactionAsync();
            try
            {
                // 参数校验
                if (permissionsDto == null)
                {
                    return ResponseReturnsEntity<bool>.Fail("权限信息不能为空");
                }
                if (string.IsNullOrEmpty(permissionsDto.PermissionsName))
                {
                    return ResponseReturnsEntity<bool>.Fail("权限名称不能为空");
                }

                var entity = new Permissions
                {
                    Id = Guid.NewGuid().ToString(),
                    ParentId = permissionsDto.ParentId,
                    PermissionsName = permissionsDto.PermissionsName,
                    PermissionsPath = permissionsDto.PermissionsPath,
                    SortId = permissionsDto.SortId,
                    State = permissionsDto.State,
                    CreateTime = DateTime.Now
                };
                var result = await _permissionsRepository.InsertEntityAsync(entity);

                await transaction.CommitAsync();
                return ResponseReturnsEntity<bool>.Success(result > 0);
            }
            catch (DbUpdateException dbEx)
            {
                await transaction.RollbackAsync();
                _logger.LogError($"数据库更新异常，添加权限失败: {dbEx.Message}", dbEx);
                return ResponseReturnsEntity<bool>.Fail("数据库操作异常，添加权限失败，请检查数据有效性或联系管理员。");
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                _logger.LogError($"添加权限失败: {ex.Message}", ex);
                return ResponseReturnsEntity<bool>.Fail($"添加权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改权限，包含异常处理
        /// </summary>
        /// <param name="permissionsDto">权限信息</param>
        /// <returns>操作结果</returns>
        /// <remarks>
        /// 1. 包含参数校验和存在性检查。
        /// 2. 捕获数据库异常和通用异常，记录详细日志。
        /// </remarks>
        public async Task<ResponseReturnsEntity<bool>> UptPermissions(PermissionsListDto permissionsDto)
        {
            try
            {
                // 参数校验
                if (permissionsDto == null)
                {
                    return ResponseReturnsEntity<bool>.Fail("权限信息不能为空");
                }
                if (string.IsNullOrEmpty(permissionsDto.Id))
                {
                    return ResponseReturnsEntity<bool>.Fail("权限ID不能为空");
                }
                if (string.IsNullOrEmpty(permissionsDto.PermissionsName))
                {
                    return ResponseReturnsEntity<bool>.Fail("权限名称不能为空");
                }

                var entity = await _permissionsRepository.GetEntityByIdAsync(new Permissions { Id = permissionsDto.Id });
                if (entity == null)
                {
                    return ResponseReturnsEntity<bool>.Fail("权限不存在");
                }

                entity.ParentId = permissionsDto.ParentId;
                entity.PermissionsName = permissionsDto.PermissionsName;
                entity.PermissionsPath = permissionsDto.PermissionsPath;
                entity.SortId = permissionsDto.SortId;
                entity.State = permissionsDto.State;
                entity.ModifyTime = DateTime.Now;

                var result = await _permissionsRepository.UpdateEntityAsync(entity);
                return ResponseReturnsEntity<bool>.Success(result > 0);
            }
            catch (DbUpdateException dbEx)
            {
                _logger.LogError($"数据库更新异常，更新权限失败: {dbEx.Message}", dbEx);
                return ResponseReturnsEntity<bool>.Fail("数据库操作异常，更新权限失败，请检查数据有效性或联系管理员。");
            }
            catch (Exception ex)
            {
                _logger.LogError($"更新权限失败: {ex.Message}", ex);
                return ResponseReturnsEntity<bool>.Fail($"更新权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除权限（软删除），包含异常处理
        /// </summary>
        /// <param name="id">权限Id</param>
        /// <returns>操作结果</returns>
        /// <remarks>
        /// 1. 包含参数校验和存在性检查。
        /// 2. 捕获数据库异常和通用异常，记录详细日志。
        /// </remarks>
        public async Task<ResponseReturnsEntity<bool>> DeletePermissions(string id)
        {
            try
            {
                // 参数校验
                if (string.IsNullOrEmpty(id))
                {
                    return ResponseReturnsEntity<bool>.Fail("权限ID不能为空");
                }

                var entity = await _permissionsRepository.GetEntityByIdAsync(new Permissions { Id = id });
                if (entity == null)
                {
                    return ResponseReturnsEntity<bool>.Fail("权限不存在");
                }

                if (entity.IsDelete)
                {
                    return ResponseReturnsEntity<bool>.Fail("权限已被删除，请勿重复操作");
                }

                entity.IsDelete = true;
                entity.ModifyTime = DateTime.Now;

                var result = await _permissionsRepository.UpdateEntityAsync(entity);
                return ResponseReturnsEntity<bool>.Success(result > 0);
            }
            catch (DbUpdateException dbEx)
            {
                _logger.LogError($"数据库更新异常，删除权限失败: {dbEx.Message}", dbEx);
                return ResponseReturnsEntity<bool>.Fail("数据库操作异常，删除权限失败，请检查数据有效性或联系管理员。");
            }
            catch (Exception ex)
            {
                _logger.LogError($"删除权限失败: {ex.Message}", ex);
                return ResponseReturnsEntity<bool>.Fail($"删除权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取权限
        /// </summary>
        public async Task<ResponseReturnsEntity<PermissionsListDto>> GetPermissionsById(string id)
        {
            var entity = await _permissionsRepository.GetEntityByIdAsync(new Permissions { Id = id });
            if (entity == null) return ResponseReturnsEntity<PermissionsListDto>.Fail("权限不存在");
            var dto = new PermissionsListDto
            {
                Id = entity.Id,
                ParentId = entity.ParentId,
                PermissionsName = entity.PermissionsName,
                PermissionsPath = entity.PermissionsPath,
                SortId = entity.SortId,
                State = entity.State,
                CreateTime = entity.CreateTime
            };
            return ResponseReturnsEntity<PermissionsListDto>.Success(dto);
        }

        /// <summary>
        /// 修改权限状态
        /// </summary>
        public async Task<ResponseReturnsEntity<bool>> UpdatePermissionsState(string id, bool state)
        {
            var entity = await _permissionsRepository.GetEntityByIdAsync(new Permissions { Id = id });
            if (entity == null) return ResponseReturnsEntity<bool>.Fail("权限不存在");
            if (entity.State == state)
            {
                string status = state ? "启用" : "禁用";
                return ResponseReturnsEntity<bool>.Fail($"当前状态已是{status}，请勿重复操作");
            }
            entity.State = state;
            var result = await _permissionsRepository.UpdateEntityAsync(entity);
            return ResponseReturnsEntity<bool>.Success(result > 0);
        }
    }
}